package com.zlw.rabbitmq.api.ack;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.Map;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/12/24 0:29
 */
public class MyChannel extends DefaultConsumer {
    /**
     * Constructs a new instance and records its association to the passed-in channel.
     *
     * @param channel the channel to which this consumer is attached
     */
    private Channel channel;

    public MyChannel(Channel channel) {
        super(channel);
        this.channel = channel;
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        //super.handleDelivery(consumerTag, envelope, properties, body);
        System.err.println("--------------------------------------");
        System.out.println("consumerTag : " + consumerTag);
        System.out.println("envelope : " + envelope.toString());
        System.out.println("properties : " + properties);
        System.out.println("body : " + new String(body));
        //进行消息确认
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, Object> headers = properties.getHeaders();
        System.out.println("headers --> " + headers);
        Integer value1 = (Integer) headers.get("key");
        System.out.println("value1 --> " + value1);
        if (0 == value1) {
            //第三个参数 是否重回队列。
            channel.basicNack(envelope.getDeliveryTag(), false, true);
        } else {
            channel.basicAck(envelope.getDeliveryTag(), false);
        }

    }
}
